package cn.itcast.wushangxiantu.Activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import java.io.IOException;

import cn.itcast.wushangxiantu.Util;
import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class Login extends AppCompatActivity implements View.OnClickListener {

    private EditText etAccount;
    private TextView tv_password;
    private EditText etPassword;
    private Button btnLogin;
    private Button btnLogon;
    private Button btnQuit;
    private static User user;
    private WebView webView;
    private Button btnXiaZai;
    public static SharedPreferences sp;
    private Animation rotateAnimation;
    private ImageView iv;
    private Button btnCopy;
    private TextView tvDaQu;
    private Spinner spinDaQu;
    private Button btnDaQu;

    public static SharedPreferences getSp() {
        return sp;
    }

    int num = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        if (Util.netWorkCheck(this)) {
            ToastUtil.toast(this, "网络正常");
            getVerName();
        } else {
            GeneralDialog("网络详情", "请联网", 0);
        }
    }

    private void initView() {
        etAccount = (EditText) findViewById(R.id.etAccount);
        tv_password = (TextView) findViewById(R.id.tv_password);
        etPassword = (EditText) findViewById(R.id.etPassword);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLogon = (Button) findViewById(R.id.btnLogon);
        btnQuit = (Button) findViewById(R.id.btnQuit);

        btnLogin.setOnClickListener(this);
        btnLogon.setOnClickListener(this);
        btnQuit.setOnClickListener(this);
        sp = getSharedPreferences("data", MODE_PRIVATE);
        int URL = sp.getInt("url", 0);
        OkhttpUtil.URL_LOG=OkhttpUtil.URL_LOGs[URL];
        String username = sp.getString("usernumber", "");
        String password = sp.getString("password", "");
        etAccount.setText(username);
        etPassword.setText(password);
        if (user == null) {
            user = new User();
        } else {
            etPassword.setText(user.getPassword());
            etAccount.setText(user.getUsernumber());
        }


        webView = (WebView) findViewById(R.id.webView);
        webView.setOnClickListener(this);
        iv = (ImageView) findViewById(R.id.iv);
        btnCopy = (Button) findViewById(R.id.btnCopy);
        btnCopy.setOnClickListener(this);
        tvDaQu = (TextView) findViewById(R.id.tvDaQu);
        spinDaQu = (Spinner) findViewById(R.id.spinDaQu);
        btnDaQu = (Button) findViewById(R.id.btnDaQu);
        btnDaQu.setOnClickListener(this);
        tvDaQu.setText("当前："+(URL+1)+"区");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnLogin:
                try {
                    submit();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btnLogon:
                Intent intent = new Intent(getApplicationContext(), Logon.class);
                startActivity(intent);
                finish();
                break;
            case R.id.btnQuit:
                finish();
                break;

            case R.id.btnCopy:
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText("746595604");
                Toast.makeText(this, "复制成功。", Toast.LENGTH_LONG).show();
                break;
            case R.id.btnDaQu:
                int num=spinDaQu.getSelectedItemPosition();
                OkhttpUtil.URL_LOG=OkhttpUtil.URL_LOGs[num];
                tvDaQu.setText("当前："+(num+1)+"区");
                break;
        }
    }

    private void submit() throws Exception {
        // validate
        String etAccountString = etAccount.getText().toString().trim();
        if (TextUtils.isEmpty(etAccountString)) {
            Toast.makeText(this, "账号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String etPasswordString = etPassword.getText().toString().trim();
        if (TextUtils.isEmpty(etPasswordString)) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (rotateAnimation == null) {
            rotateAnimation = AnimationUtils.loadAnimation(this,R.anim.rotate_animation);
            iv.setVisibility(View.VISIBLE);
            iv.startAnimation(rotateAnimation);
        }else {
            iv.setVisibility(View.INVISIBLE);
            iv.clearAnimation();
            rotateAnimation=null;
        }
        getDate(etAccountString, etPasswordString);


    }

    private void getDate(final String userName, final String passWord) throws Exception {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userName=" + userName + "&passWord=" + passWord + "&need=denglu" + "&banben=" + getVerName(this), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("Login111", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("Login222", src);
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {
                    user = null;
                }
                Message message = new Message();
                message.obj = user;
                message.what = 1;
                Log.v("123213213213", user.getDj() + "");
                handler.sendMessage(message);
            }
        });
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            if (rotateAnimation != null) {
                iv.setVisibility(View.INVISIBLE);
                iv.clearAnimation();
            }
            switch (message.what) {
                case 1:
                    user = (User) message.obj;
                    if (null != user) {
                        if (user.getStw().equals("Yes")) {
                            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                            cunchu();
                            ToastUtil.toast(Login.this, "登陆成功");
                            startActivity(intent);
                            finish();
                        } else if (user.getStw().equals("No1")) {
                            GeneralDialog("登陆失败", "账号不存在", 0);
                        } else if (user.getStw().equals("No2")) {
                            GeneralDialog("登陆失败", "密码错误", 0);
                        } else if (user.getStw().equals("No")) {
                            GeneralDialog("登陆失败", "请跟新至最高版本", 1);
                        }
                    } else {
                        GeneralDialog("登陆失败", "服务器炸了", 0);
                    }
                    break;
                case 2:
                    user = (User) message.obj;
                    if (null != user) {
                        if (user.getStw().equals(getVerName(Login.this))) {
                            ToastUtil.toastLong(Login.this, "当前已为最新版本" + getVerName(Login.this));
                        } else {
                            GeneralDialog("登陆失败", "当前版本：" + getVerName(Login.this) + "\n最新版本：" + user.getStw(), 1);
                        }
                    } else {
                        GeneralDialog("登陆失败", "服务器炸了", 0);
                    }
                    break;
            }
            return false;
        }
    });

    private void cunchu() {

        SharedPreferences sp = getSharedPreferences("data", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("usernumber", user.getUsernumber());
        editor.putString("password", user.getPassword());
        editor.putInt("url",spinDaQu.getSelectedItemPosition());
        editor.commit();
    }


    public static User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void GeneralDialog(String head, String content, final int num) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        String text = "确认";
        if (num == 1) {
            text = "更新游戏";
        }
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(head)
                .setMessage(content)
                .setPositiveButton(text, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        if (num == 1) {
                            WebView webView = (WebView) findViewById(R.id.wv_webview);
                            Intent intent;
                            intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_url = Uri.parse("http://" + OkhttpUtil.URL_SOCKET + ":8081/wushangxiantu.apk");
                            intent.setData(content_url);
                            startActivity(intent);
                            intent.setData(content_url);
                        }
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    public static boolean netWorkCheck(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info != null) {
            return info.isConnected();
        } else {
            return false;
        }
    }

    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    public void getVerName() {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=getVerName", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("Login111", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("Login222", src);
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {
                    user = null;
                }
                Message message = new Message();
                message.obj = user;
                message.what = 2;
                handler.sendMessage(message);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        if (rotateAnimation != null ) {
            rotateAnimation=null;
        }
        iv.clearAnimation();
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        if (checkDoubleClick(intent)) {
            super.startActivityForResult(intent, requestCode);

        }
    }

    private String mActivityJumpTag;        //activity跳转tag
    private long mClickTime;

    private boolean checkDoubleClick(Intent intent) {
        // 默认检查通过
        boolean result = true;
        // 标记对象
        String tag;
        if (intent.getComponent() != null) { // 显式跳转
            tag = intent.getComponent().getClassName();
        } else if (intent.getAction() != null) { // 隐式跳转
            tag = intent.getAction();
        } else {
            return true;
        }

        if (tag.equals(mActivityJumpTag) && mClickTime >= SystemClock.uptimeMillis() - 500) {
            // 检查不通过
            result = false;
        }

        // 记录启动标记和时间
        mActivityJumpTag = tag;
        mClickTime = SystemClock.uptimeMillis();
        return result;

    }
}
